package cac.fenjian.resource.WmsDeliveryCoordinateBasic.rest;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.common.DateUtil;
import cac.fenjian.resource.WmsDeliverPlan.dto.WmsDeliverPlanDTO;
import cac.fenjian.resource.WmsDeliveryCoordinateBasic.service.WmsDeliveryCoordinateService;
import com.alibaba.fastjson.JSON;
import com.cac.dme.adapter.rest.msg.PageParameter;
import com.cac.dme.adapter.rest.msg.QueryReqBean;
import com.cac.dme.adapter.rest.msg.QueryRespBean;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.cac.dme.adapter.utils.ComUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/WmsDeliveryCo")
@Slf4j
public class WmsDeliveryCoordinateRest {

    @Autowired
    private WmsDeliveryCoordinateService wmsDeliveryCoordinateService;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @PostMapping("/deletDto")
    public ResponseMsg<Map> deleteMany(@RequestBody HashMap<String, Object> map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap<String, Object>> ids = (List<HashMap<String, Object>>) map.get("data");
        for (int i = 0; i < ids.size(); i++) {
            HashMap<String, Object> map1 = ids.get(i);
            String id = (String) map1.get("wmsDeliveryCoordinateId");
            String status = (String) map1.get("status");
            if ("协调中".equals(status)) {
                if (map1.get("wmsDeliveryCoordinateId") != null) {
                    wmsDeliveryCoordinateService.deleteDtoById(id);
                    responseMsg.setRetCode("200");
                    responseMsg.setMessage("删除成功！");
                }
            }else {
                responseMsg.setRetCode("201");
                responseMsg.setMessage("删除失败！只能删除协调中的数据!");
            }
        }
        responseMsg.setResponseBody(reMsg);
        return responseMsg;
    }

    //创建协调单
    @PostMapping("/insertDto")
    public ResponseMsg<String> insertWmsDeliveryCo(@RequestBody HashMap hashMap) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        int sucess=0,error=0;
        StringBuilder mesCheckQualiticationIds = new StringBuilder();
        try {

            if (hashMap.get("problemType") == null||hashMap.get("problemType").equals("")) {
                return responseMsg.setMessage("问题类型不能为空!").setRetCode("201");
            } else if (hashMap.get("problemContent") == null||hashMap.get("problemContent").equals("")) {
                return responseMsg.setMessage("问题内容不能为空!").setRetCode("201");
            } else {
                List<HashMap> deliverys = (List<HashMap>) hashMap.get("wmsDeliveryPlans");
                for(HashMap delivery : deliverys){
                    ////2023-08-02 yebo 新增，无库存交接不需要发起协调单
                    int noinvstatus = wmsDeliveryCoordinateService.queryIsNoInvDelivery(delivery);
                    if(noinvstatus>0){
                        error++;
                        continue;
                    }
                    //2023-11-07lqc bzj不发起协调
                    int BzjCount = wmsDeliveryCoordinateService.searchIsBzj(delivery);
                    if(BzjCount>0){
                        error++;
                        continue;
                    }
                    //1:查询是否发起协调
                    int isCoor = wmsDeliveryCoordinateService.searchIsCoordinate(delivery);
                    if(isCoor>0){
                        mesCheckQualiticationIds.append(delivery.get("mesCheckQualiticationId")).append(",");
                        error++;
                        continue;
                    }
                    //2：写入协调表
                    delivery.put("wmsDeliveryCoordinateId",ComUtil.getId());
                    delivery.put("createdBy",hashMap.get("applyEmpcode"));
                    delivery.put("creationDate",DateUtil.nowTime());
                    delivery.put("applyDate",DateUtil.nowTime());
                    delivery.put("status","0");
                    delivery.put("isEff","1");
                    delivery.put("problemType",hashMap.get("problemType"));
                    delivery.put("problemContent",hashMap.get("problemContent"));
                    wmsDeliveryCoordinateService.insertWmsDeliveryCo(delivery);
                    sucess++;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(error>0){
            responseMsg.setMessage("创建成功"+sucess+"条，失败"+error+"条！"+mesCheckQualiticationIds.toString()+"已经发起了协调或无库存交接不需要发起协调");
        }else{
            responseMsg.setMessage("创建成功"+sucess+"条！");
        }
        return responseMsg.setRetCode("200");
    }


    //协调单查询
    @PostMapping("/searchWmsDelCo")
    public ResponseMsg<QueryRespBean<List<HashMap>>> searchWmsDelCoordinate(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<List<HashMap>>> responseMsg = new ResponseMsg<>();
        String startTimeParams = JSON.toJSONString(map.get("startTime"));
        String endTimeParams = JSON.toJSONString(map.get("endTime"));
        Date startTime = JSON.parseObject(startTimeParams, Date.class);
        Date endTime = JSON.parseObject(endTimeParams, Date.class);
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);
        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);
        QueryRespBean<List<HashMap>> result = wmsDeliveryCoordinateService.searchWmsDelCoordinate(queryReqBean, startTime, endTime);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    //提交归零申请
    @PostMapping("/updateWmsDeliveryCo")
    public ResponseMsg<String> updateWmsDeliveryCo(@RequestBody Map map) throws ParseException {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        int success=0,error=0;
        try {
                List<HashMap> list = (List<HashMap>) map.get("deliveryCoordinates");
                for(HashMap coordinate : list){
                    coordinate.put("endApplyEmpcode", map.get("applyEmpcode"));
                    coordinate.put("lastUpdateBy", map.get("applyEmpcode"));
                    coordinate.put("lastUpdateIp", map.get("ip"));
                    coordinate.put("endApplyDate", DateUtil.nowTime());
                    coordinate.put("lastUpdateDate", DateUtil.nowTime());
                    int result = wmsDeliveryCoordinateService.updateWmsDeliveryCo(coordinate);
                    String wmsDeliveryCoordinateId = (String) coordinate.get("wmsDeliveryCoordinateId");
                    String ip = (String) map.get("ip");
                    String userCode = (String) map.get("applyEmpcode");
                    if (result > 0) {
                        String code = "sendBData";
                        String sendScenario = "发起协调";
                        String name = "两网传输-发送业务数据";
                        String parameters = wmsDeliveryCoordinateService.sendToGK(wmsDeliveryCoordinateId, userCode, ip,(String) coordinate.get("wmsDeliveryPlanId"));
                        long beginTime = System.currentTimeMillis();
                        log.info("======开始时间=======" + beginTime);
                        callInterfaceService.sendBData(code, name, parameters,sendScenario);
                        long endTime = System.currentTimeMillis();
                        log.info("======消耗时间=======" + (endTime - beginTime) + "ms");
                        success++;
                    } else{
                        error++;
                    }
                }
        } catch (Exception e) {
            e.printStackTrace();
            return responseMsg.setMessage(e.getMessage()).setRetCode("201");
        } finally {
            if(error>0){
                responseMsg.setMessage("提交成功"+success+"条，失败"+error+"！，请检查提交数据中是否存在已发起协调的数据").setRetCode("200");
            }else{
                responseMsg.setMessage("提交成功"+success+"条！").setRetCode("200");
            }
            return responseMsg;
        }
    }

    //归零
    @PostMapping("/updateToZeroWmsDeliveryCo")
    public ResponseMsg<String> updateToZeroWmsDeliveryCo(@RequestBody Map map) throws ParseException {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        List<HashMap> list = (List<HashMap>) map.get("coordiantes");
        String result = wmsDeliveryCoordinateService.updateToZeroWmsDeliveryCo(map,list);
        return responseMsg.setMessage(result).setRetCode("200");

    }

    //交接单查询
    @PostMapping("/searchDeliverPlan")
    public ResponseMsg<QueryRespBean<List<HashMap>>> searchDeliverPlan(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<List<HashMap>>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsDeliverPlanDTO searchParams = JSON.parseObject(searchParamsParams, WmsDeliverPlanDTO.class);
        QueryReqBean<WmsDeliverPlanDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);
        QueryRespBean<List<HashMap>> result = wmsDeliveryCoordinateService.searchDeliverPlan(queryReqBean);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    //查询协调问题类型
    @PostMapping("/searchProblemType")
    public ResponseMsg<List<HashMap>> searchProblemType() {
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
        List<HashMap> map = wmsDeliveryCoordinateService.searchProblemType();
        return responseMsg.setResponseBody(map);
    }
}
